package com.lanou.moving.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.lanou.moving.R;
import com.lanou.moving.adapter.GuessYouLikeAdapter;
import com.lanou.moving.base.BaseActivity;
import com.lanou.moving.base.BaseApplication;
import com.lanou.moving.constant.URL;
import com.lanou.moving.entity.GuessYouLike;
import com.lanou.moving.entity.MusicInfo;
import com.lanou.moving.entity.dao.AddTo;
import com.lanou.moving.entity.dao.AddToDao;
import com.lanou.moving.entity.dao.Collection;
import com.lanou.moving.entity.dao.CollectionDao;
import com.lanou.moving.eventBus.MyEventBus;
import com.lanou.moving.service.DownloadServices;
import com.lanou.moving.singleton.DaoSingleton;
import com.lanou.moving.view.CDSPopupWindow;
import com.lanou.moving.volley.StringRequestUtf;
import com.lanou.moving.volley.VolleySingleton;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import it.sephiroth.android.library.picasso.Picasso;

/**
 * Created by 刘琪 on 15/11/4.
 */
public class GuessYouLikeActivity extends BaseActivity implements AdapterView.OnItemClickListener,
        View.OnClickListener, GuessYouLikeAdapter.OnMenuClickListener {
    private CollapsingToolbarLayout toolbarLayout;
    private VolleySingleton volleySingleton;
    private StringRequestUtf request;
    private Toolbar coordinator_toolbar;
    private ImageView songs_list_bg;
    private ListView songs_list_listview;
    private GuessYouLikeAdapter adapter;
    private List<GuessYouLike.DataEntity> dataEntities;
    private int id;
    private String pic_url;//图片url
    private String url;
    private int from;//数据来源
    private TextView songs_list_collection;//收藏歌单
    private TextView songs_list_share;//分享
    private LinearLayout colle_share;
    private GuessYouLike.DataEntity dataEntity;
    private String name;
    private AddToDao addToDao;//数据库表
    //数据库表
    private CollectionDao collectionDao;
    private View view;
    private TextView collect_tv;
    private ImageView rankingListBackground;
    private List<Collection> collections;
    private CDSPopupWindow pw;
    private int index = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ranking_list_detail);
        BaseApplication.getInstance().addActivity(this);
        addToDao = DaoSingleton.getInstance().getAddToDao();
        collectionDao = DaoSingleton.getInstance().getCollectionDao();
        initView();
        getData();
    }

    private void initView() {

        view = LayoutInflater.from(this).inflate(R.layout.layout_song, null);
        collect_tv = (TextView) view.findViewById(R.id.layout_song_collection);
        rankingListBackground = (ImageView) findViewById(R.id.new_song_background);

        Intent intent = getIntent();
        id = intent.getIntExtra("id", 0);
        pic_url = intent.getStringExtra("pic_url");
        name = intent.getStringExtra("name");
        from = intent.getIntExtra("from", 0);
        volleySingleton = VolleySingleton.getInstance(this);



        toolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
        toolbarLayout.setTitle(name);

        songs_list_bg = (ImageView) findViewById(R.id.songs_list_bg);
        Picasso.with(this).load(pic_url).placeholder(R.mipmap.songlist_cover)
                .error(R.mipmap.songlist_cover).into(songs_list_bg);

        songs_list_listview = (ListView) findViewById(R.id.songs_list_listview);
        songs_list_listview.setOnItemClickListener(this);

        coordinator_toolbar = (Toolbar) findViewById(R.id.coordinator_toolbar);
        coordinator_toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        colle_share = (LinearLayout) findViewById(R.id.colle_share);

        songs_list_collection = (TextView) findViewById(R.id.songs_list_collection);
        songs_list_collection.setOnClickListener(this);

        songs_list_share = (TextView) findViewById(R.id.songs_list_share);
    }

    private void getData() {
        if (from == 13) {
            url = URL.TYPE_TWENTYONE_START + id + URL.TYPE_TWENTYONE_END;
        }
        if (from == 21) {
            url = URL.TYPE_THIRTEEN_START + id + URL.TYPE_THIRTEEN_END;
        }
        if (from == 22) {
            url = URL.TYPE_TWENTYTWO;
            colle_share.setVisibility(View.GONE);
        }
        request = new StringRequestUtf(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                GuessYouLike data = gson.fromJson(response, GuessYouLike.class);
                dataEntities = data.getData();
                adapter = new GuessYouLikeAdapter(GuessYouLikeActivity.this, dataEntities);
                adapter.setOnMenuClickListener(GuessYouLikeActivity.this);
                songs_list_listview.setAdapter(adapter);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        volleySingleton.addQueue(request);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        dataEntity = (GuessYouLike.DataEntity) parent.getItemAtPosition(position);
        if (dataEntity.getUrlList() != null && dataEntity.getUrlList().size() > 0) {
            List<MusicInfo> musicInfoList = new ArrayList<>();
            for (GuessYouLike.DataEntity entity : dataEntities) {
                if (entity.getUrlList() != null && entity.getUrlList().size() > 0) {
                    MusicInfo musicInfo = new MusicInfo();
                    musicInfo.setSongName(entity.getName());
                    musicInfo.setAlbum(entity.getAlbumName());
                    musicInfo.setAlbumId(entity.getAlbumId());
                    musicInfo.setUrl(entity.getUrlList().get(0).getUrl());
                    musicInfo.setDuration(entity.getUrlList().get(0).getDuration());
                    musicInfo.setSingerName(entity.getSingerName());
                    musicInfo.setResouce("网络");
                    musicInfoList.add(musicInfo);
                }
            }

            Intent intent = new Intent(GuessYouLikeActivity.this, PlayMusicActivity.class);
            EventBus.getDefault().post(new MyEventBus.Deliver(musicInfoList, dataEntity.getName()));
            intent.putExtra("songName", dataEntity.getName());
            intent.putExtra("duration", dataEntity.getUrlList().get(0).getDuration());
            intent.putExtra("resource", "网络");
            intent.putExtra("albumId", dataEntity.getAlbumId());
            intent.putExtra("singerName", dataEntity.getSingerName());
            startActivity(intent);
        } else {
            Toast.makeText(this, "暂时无法播放此歌曲", Toast.LENGTH_LONG).show();
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        List<AddTo> lists = addToDao.queryBuilder().where(AddToDao.Properties.SongListId.eq(id)).list();
        if (lists != null && lists.size() > 0) {
            songs_list_collection.setText("取消收藏");
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.songs_list_collection:
                if ("收藏".equals(songs_list_collection.getText())) {
                    AddTo addTo = new AddTo();
                    addTo.setName(name);
                    addTo.setSongListId(id);
                    addTo.setPicUrl(pic_url);
                    addTo.setSongs(dataEntities.size());
                    addTo.setResource("歌单");
                    addToDao.insert(addTo);
                    songs_list_collection.setText("取消收藏");
                    Toast.makeText(this, "已加入收藏", Toast.LENGTH_LONG).show();
                } else if ("取消收藏".equals(songs_list_collection.getText())) {
                    addToDao.queryBuilder().where(AddToDao.Properties.SongListId.eq(id)).buildDelete()
                            .executeDeleteWithoutDetachingEntities();
                    songs_list_collection.setText("收藏");
                }
                break;
        }
    }

    @Override
    public void onMenuClick(final GuessYouLike.DataEntity songsEntity) {
        rankingListBackground.setVisibility(View.VISIBLE);
        collections = collectionDao.queryBuilder().where(
                CollectionDao.Properties.SongId.eq(songsEntity.getSongId())).list();
        if (collections != null && collections.size() > 0) {
            collect_tv.setText("取消收藏");
        } else {
            collect_tv.setText("收藏");
        }
        pw = new CDSPopupWindow(this, view, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.layout_song_collection:
                        if ("收藏".equals(collect_tv.getText())) {
                            Collection collection = new Collection();
                            collection.setSongId(songsEntity.getSongId());
                            collection.setSongName(songsEntity.getName());
                            collection.setPlayUrl(songsEntity.getUrlList().get(0).getUrl());
                            collection.setAlbumId(songsEntity.getAlbumId());
                            collection.setDuration(songsEntity.getUrlList().get(0).getDuration());
                            collection.setSingerName(songsEntity.getSingerName());
                            collectionDao.insert(collection);
                            collect_tv.setText("取消收藏");
                            Toast.makeText(GuessYouLikeActivity.this, "已收藏", Toast.LENGTH_LONG).show();
                            pw.dismiss();
                        } else if ("取消收藏".equals(collect_tv.getText())) {
                            collectionDao.queryBuilder().where(CollectionDao.Properties.SongId
                                    .eq(songsEntity.getSongId())).buildDelete()
                                    .executeDeleteWithoutDetachingEntities();
                            collect_tv.setText("收藏");
                            Toast.makeText(GuessYouLikeActivity.this, "已取消收藏", Toast.LENGTH_LONG).show();
                            pw.dismiss();
                        }
                        break;
                    case R.id.layout_song_download:
                        if (songsEntity.getAuditionList() == null ||
                                songsEntity.getAuditionList().size() == 0 ||
                                songsEntity.getAuditionList().size() == 1) {
                            Toast.makeText(GuessYouLikeActivity.this, "暂无资源", Toast.LENGTH_LONG).show();
                        } else if (songsEntity.getAuditionList().size() > 1) {

                            String download_url = songsEntity.getAuditionList().get(1).getUrl();
                            Log.i("download_url", songsEntity.getUrlList().get(0).getUrl());
                            startDownloadService(index, download_url, songsEntity.getName(), songsEntity.getSingerName());
                            index++;
                            pw.dismiss();
                        }
                        break;
                    case R.id.layout_song_share:
                        break;
                }

            }
        }, rankingListBackground);
        pw.showAtLocation(findViewById(R.id.coordinator_layout), Gravity.CENTER, 0, 0);
    }

    private void startDownloadService(int notifyId, String url, String songName, String singerName) {     //绑定服务类
        Intent intent = new Intent(GuessYouLikeActivity.this, DownloadServices.class);
        intent.putExtra("url", url);
        intent.putExtra("singerName", singerName);
        intent.putExtra("songName", songName);
        intent.putExtra("notifyId", notifyId);
        startService(intent);
    }
}
